<template>
  <el-card class="blacklist-manage">
    <h2>黑名单管理</h2>

    <!-- 搜索 & 导出 -->
    <div class="filter-row">
      <el-input
          v-model="searchKeyword"
          placeholder="姓名或工号搜索"
          clearable
          style="width: 240px"
      />
      <el-button @click="exportCSV" type="success">导出数据</el-button>
    </div>

    <!-- 表格 -->
    <el-table
        v-loading="store.loading"
        :data="paginatedList"
        stripe
        empty-text="暂无数据"
        style="width: 100%"
    >
      <el-table-column prop="userName" label="用户姓名" width="120" />
      <el-table-column prop="userId"   label="工号"       width="120" />
      <el-table-column prop="reason"   label="拉黑原因" />

      <el-table-column label="触发类型">
        <template #default="{ row }">
          {{ triggerLabels[row.triggerType] }}
        </template>
      </el-table-column>

      <el-table-column label="开始时间">
        <template #default="{ row }">
          {{ formatDate(row.startDate) }}
        </template>
      </el-table-column>
      <el-table-column label="解封时间">
        <template #default="{ row }">
          {{ formatDate(row.endDate) }}
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.active ? 'danger' : 'success'" size="small">
            {{ row.active ? '生效中' : '已解封' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
              v-if="row.active"
              size="small"
              type="primary"
              @click="handleUnban(row.id)"
          >解封</el-button>
          <el-button
              v-if="row.active"
              size="small"
              @click="openExtend(row)"
          >延长</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30]"
          :total="filteredList.length"
          layout="prev, pager, next, sizes, total"
          @current-change="currentPage = $event"
          @size-change="onPageSizeChange"
      />
    </div>

    <!-- 延长对话框 -->
    <el-dialog v-model="dialogVisible" title="延长封禁">
      <el-form>
        <el-form-item label="延长天数">
          <el-input-number v-model="extendDays" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExtend">确认</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useBlacklistStore } from '../../stores/blacklist'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const store = useBlacklistStore()

// 搜索关键字
const searchKeyword = ref('')

// 分页
const currentPage = ref(1)
const pageSize    = ref(10)

// 延长弹窗
const dialogVisible = ref(false)
const extendDays    = ref(7)
let   currentId: number | null = null

// 触发类型中文映射
const triggerLabels: Record<string,string> = {
  NO_SHOW:   '多次未签到',
  MALICIOUS: '恶意占用'
}

// 日期格式化
const formatDate = (s: string) => dayjs(s).format('YYYY-MM-DD')

// 初始拉列表
onMounted(() => {
  store.fetchList()
})

// 过滤后的列表
const filteredList = computed(() => {
  const kw = searchKeyword.value.trim().toLowerCase()
  return store.list.filter(r =>
      r.userName.includes(kw) ||
      r.userId.includes(kw)
  )
})

// 当前页要显示的数据
const paginatedList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredList.value.slice(start, start + pageSize.value)
})

// 切换页大小时重设页码
function onPageSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
}

// 导出 CSV
function exportCSV() {
  const header = ['用户姓名','工号','拉黑原因','触发类型','开始时间','解封时间','状态']
  const rows = filteredList.value.map(r => [
    r.userName,
    r.userId,
    r.reason,
    triggerLabels[r.triggerType],
    formatDate(r.startDate),
    formatDate(r.endDate),
    r.active ? '生效中' : '已解封'
  ])
  const csv = [header, ...rows].map(r => r.join(',')).join('\n')
  const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '黑名单.csv'
  link.click()
}

// 立即解封
async function handleUnban(id: number) {
  try {
    await store.unban(id)
    ElMessage.success('解封成功')
  } catch {
    ElMessage.error('解封失败')
  }
}

// 打开延长对话框
function openExtend(row: { id: number }) {
  currentId = row.id
  extendDays.value = 7
  dialogVisible.value = true
}

// 确认延长
async function confirmExtend() {
  if (!currentId) return
  try {
    // 调用后端 mock 接口
    await store.extendBan(currentId, extendDays.value)
    const item = store.list.find(r => r.id === currentId)
    if (item) {
      item.endDate = dayjs(item.endDate)
          .add(extendDays.value, 'day')
          .format('YYYY-MM-DD')
    }
    ElMessage.success('延长成功')
    dialogVisible.value = false
  } catch {
    ElMessage.error('延长失败')
  }
}
</script>

<style scoped>
.blacklist-manage { padding: 16px; }
.filter-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}
.pagination-wrap {
  margin-top: 16px;
  text-align: right;
}
</style>
